import UIKit
import AssetsLibrary

public class ImagePickerHelp: NSObject {
    
    typealias ALAssetsGroupType = UInt32
    
    static var authorizationStatus: Bool {
        let currentStatus = ALAssetsLibrary.authorizationStatus()
        return currentStatus != .Authorized && currentStatus != .NotDetermined
    }
    
    private lazy var defaultAssetsLibrary: ALAssetsLibrary = {
        return ALAssetsLibrary()
    }()
    
    init(type: ALAssetsGroupType, filter: ALAssetsFilter, isSuccess: (status: Bool,albums: [Album]) -> Void) {
        super.init()
        
        refreshImages(type, filter: filter) { (status, albums) in
            isSuccess(status: status, albums: albums)
        }
    }
    
    func refreshImages(type: ALAssetsGroupType, filter: ALAssetsFilter, isSuccess: (status: Bool,albums: [Album]) -> Void) {
        if ImagePickerHelp.authorizationStatus {
            isSuccess(status: false, albums: [])
            return
        }
        var albums: [Album] = []
        defaultAssetsLibrary.enumerateGroupsWithTypes(type, usingBlock: { (group, stop) in
            if let group = group {
                group.setAssetsFilter(filter)
                let album = Album(group: group)
                albums.append(album)
                return
            }
            
            isSuccess(status: true, albums: albums)
        }) { (error) in
            isSuccess(status: false, albums: [])
        }
    }
    
    deinit {
        // print("ImagePickerHelp: deinit")
    }
}
